package com.jhgsys.internal.formDesign.controller;

import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.formDesign.dto.FormDesignDto;
import com.jhgsys.internal.formDesign.entity.FormDesign;
import com.jhgsys.internal.formDesign.service.IFormDesignService;
import com.jhgsys.internal.system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

/**
 * 表单设计 Controller
 *
 * @author fenghaijun
 * @date 2024-08-28 10:54:00
 */
@Slf4j
@Validated
@Controller
public class FormDesignController extends BaseController {

    @Autowired
    private IFormDesignService formDesignService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "formDesign")
    @RequiresPermissions("formDesign:view")
    public String formDesignIndex(Model model){
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        return FebsUtil.view("formDesign/formDesign/formDesignList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "formDesign/add")
    @RequiresPermissions("formDesign:add")
    public String formDesignAdd(){ return FebsUtil.view("formDesign/formDesign/formDesignEdit");}

    @GetMapping(FebsConstant.VIEW_PREFIX + "formPreview")
    @RequiresPermissions("formDesign:add")
    public String formPreview(){
        return FebsUtil.view("formDesign/formDesign/formPreview");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "formDesign/update/{id}")
    @RequiresPermissions("formDesign:edit")
    public String formDesignUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("formDesign", formDesignService.findFormDesignById(id));
        return FebsUtil.view("formDesign/formDesign/formDesignEdit");
    }

    /**
     * 查询（所有）
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     */
    @GetMapping("formDesign")
    @ResponseBody
    @RequiresPermissions("formDesign:view")
    public FebsResponse getAllFormDesigns(FormDesign formDesign) {
        return new FebsResponse().success().data(formDesignService.findFormDesignList(formDesign));
    }

    /**
     * 查询（分页）
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     */
    @GetMapping("formDesign/list")
    @ResponseBody
    @RequiresPermissions("formDesign:view")
    public FebsResponse formDesignList(QueryRequest request, FormDesignDto formDesignDto) {
        Map<String, Object> dataTable = getDataTable(this.formDesignService.findFormDesignPage(request, formDesignDto));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 表单录入查询（分页）
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     */
    @GetMapping("formDesignFill/list")
    @ResponseBody
    @RequiresPermissions("formFill:view")
    public FebsResponse formFillList(QueryRequest request, FormDesignDto formDesignDto) {
        User currentUser = getCurrentUser();
        List<User> userList = Collections.singletonList(currentUser);
        formDesignDto.setUserList(userList);
        Map<String, Object> dataTable = getDataTable(this.formDesignService.findFormFillPage(request, formDesignDto));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 FormDesign
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     */
    @Log("新增FormDesign")
    @PostMapping("formDesign")
    @ResponseBody
    @RequiresPermissions("formDesign:add")
    public FebsResponse addFormDesign(@RequestBody @Valid FormDesignDto formDesignDto) throws FebsException {
        try {
            formDesignDto.setCreatedBy(getCurrentUser().getUserName());
            this.formDesignService.createFormDesign(formDesignDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增FormDesign失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 FormDesign
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     */
    @Log("逻辑删除FormDesign")
    @GetMapping("formDesign/delete/{id}")
    @ResponseBody
    @RequiresPermissions("formDesign:delete")
    public FebsResponse deleteFormDesign(@PathVariable("id") String formDesignIds) throws FebsException {
        try {
            FormDesign formDesign = new FormDesign();
            formDesign.setDeletedBy(getCurrentUser().getUserName());
            formDesign.setDeletedTime(new Date());
            formDesign.setDeletedFlg(FebsConstant.INVALID);
            this.formDesignService.deleteFormDesign(formDesign,formDesignIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除FormDesign失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
    * 物理删除 FormDesign
    * @author fenghaijun
    * @date 2024-08-28 10:54:00
    */
    @Log("物理删除FormDesign")
    @GetMapping("formDesign/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("formDesign:delete")
    public FebsResponse physicallyDeleteFormDesign(@PathVariable("id") String formDesignIds) throws FebsException {
        try {
            this.formDesignService.physicallyDeleteFormDesign(formDesignIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除FormDesign失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修改 FormDesign
     * @author fenghaijun
     * @date 2024-08-28 10:54:00
     */
    @Log("修改FormDesign")
    @PostMapping("formDesign/update")
    @ResponseBody
    @RequiresPermissions("formDesign:edit")
    public FebsResponse updateFormDesign(@RequestBody FormDesignDto formDesignDto) throws FebsException {
        try {
            formDesignDto.setUpdatedBy(getCurrentUser().getUserName());
            this.formDesignService.updateFormDesign(formDesignDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改FormDesign失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
    /**
     * 修改发布状态
     * @param formDesign
     * @return
     * @throws FebsException
     */
    @Log("修改发布状态")
    @PostMapping("formDesign/updateStatus")
    @ResponseBody
    @RequiresPermissions(value={"formDesign:edit"},logical= Logical.OR)
    public FebsResponse updatePostStatus(FormDesign formDesign) throws FebsException {
        try {
            if(StringUtils.isBlank(formDesign.getDesignId())){
                return new FebsResponse().fail().message("表单Id不能为空！");
            }
            if(StringUtils.isBlank(formDesign.getStatus())){
                return new FebsResponse().fail().message("表单状态不能为空！");
            }
            formDesign.setUpdatedBy(getCurrentUser().getUserName());
            formDesign.setUpdatedTime(new Date());

            this.formDesignService.updateById(formDesign);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改表单状态失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
    /**
     * 修改是否设为模板
     * @param formDesign
     * @return
     * @throws FebsException
     */
    @Log("修改是否设为模板")
    @PostMapping("formDesign/updateTemplateFlg")
    @ResponseBody
    @RequiresPermissions(value={"formDesign:edit"},logical= Logical.OR)
    public FebsResponse updatePostTemplateFlg(FormDesign formDesign) throws FebsException {
        try {
            if(StringUtils.isBlank(formDesign.getDesignId())){
                return new FebsResponse().fail().message("表单Id不能为空！");
            }
            if(StringUtils.isBlank(formDesign.getTemplateFlg())){
                return new FebsResponse().fail().message("表单是否设为模板不能为空！");
            }
            formDesign.setUpdatedBy(getCurrentUser().getUserName());
            formDesign.setUpdatedTime(new Date());

            this.formDesignService.updateById(formDesign);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改表单是否为模板失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }
}
